package com.sh.caryr.erp.service.impl.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sh.caryr.erp.entity.user.UserRole;
import com.sh.caryr.erp.entity.user.UserRoleAuth;
import com.sh.caryr.erp.mapper.user.UserRoleAuthMapper;
import com.sh.caryr.erp.mapper.user.UserRoleMapper;
import com.sh.caryr.erp.service.IUserRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户权限表 服务实现类
 * </p>
 *
 * @author milkeeper
 * @since 2017-12-10
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserRoleAuthMapper authMapper;


    @Override
    public void getUserRoleDetail(UserRole userRole){
        Wrapper<UserRoleAuth> entityWrapper = new EntityWrapper<UserRoleAuth>().eq("roleId", userRole.getId());
        userRole.setAuthList(authMapper.selectList(entityWrapper));
    }

    @Override
    public List<UserRole> findUserRolesDynamic(Integer current, Integer size, Wrapper wrapper, String orderBy) {
        return this.findUserRolesDynamic(new Page<UserRole>(current, size), wrapper.orderBy(orderBy));
    }

    @Override
    @Transactional
    public void deleteUserRoleById(Long id) {
        UserRole userRole = this.selectById(id);
        authMapper.delete(new EntityWrapper<UserRoleAuth>().eq("roleId", userRole.getId()));
        this.deleteById(id);
    }

    private List<UserRole> findUserRolesDynamic(Page<UserRole> page, Wrapper<UserRole> wrapper) {
        List<UserRole> userRoles = userRoleMapper.selectPage(
                page,
                wrapper
        );

        for (UserRole userRole : userRoles) {
            Wrapper<UserRoleAuth> entityWrapper = new EntityWrapper<UserRoleAuth>().eq("roleId", userRole.getId());
            userRole.setAuthList(authMapper.selectList(entityWrapper));
        }
        return userRoles;
    }

}
